
import { defineStore } from 'pinia'
import { dynamicRoutes } from '@/router/dynamicRoutes/index.ts'
import { constantRoutes } from '@/router/constantRoutes/index.ts'


/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
export const useRouterStore = defineStore('router', {
  state: () => ({
    routes: [],
    addRoutes: []
  }),
  getters: {
    // doubleCount: (state) => state.count * 2,
  },
  actions: {
    generateRoutes(roles: string) {
      return new Promise(resolve => {
        let accessedRoutes
        if (roles.includes('admin')) {
          accessedRoutes = dynamicRoutes || []
        } else {
          accessedRoutes = filterAsyncRoutes(dynamicRoutes, roles)
        }
        // commit('SET_ROUTES', accessedRoutes)
        this.addRoutes = accessedRoutes
        this.routes = constantRoutes.concat(accessedRoutes)
        resolve(accessedRoutes)
      })
    }
  },
})